<template>
  <main>
    <n-form ref="loginForm" :model="user" :rules="rules" :show-label="false">
      <n-form-item path="name">
        <n-input
          v-model:value="user.name"
          :input-props="{ autocomplete: 'on' }"
          autofocus
          placeholder="请输入用户名"
          size="large"
        >
          <template #prefix>
            <n-icon :component="PersonOutline"></n-icon>
          </template>
        </n-input>
      </n-form-item>
      <n-form-item path="password">
        <n-input
          v-model:value="user.password"
          placeholder="请输入密码"
          autocomplete
          :input-props="{ autocomplete: 'off' }"
          size="large"
          type="password"
          show-password-on="click"
        >
          <template #prefix>
            <n-icon :component="LockClosedOutline"></n-icon>
          </template>
        </n-input>
      </n-form-item>
      <n-form-item>
        <n-button
          type="primary"
          size="large"
          class="w-full"
          attr-type="submit"
          @click="handleLogin()"
          >登录</n-button
        >
      </n-form-item>
    </n-form>
  </main>
</template>

<script setup>
import { reactive } from "vue";
import { PersonOutline, LockClosedOutline } from "@vicons/ionicons5";
/**
 * 导入存储
 */
import StorageService from "@/store/dataStore";

/**
 * 请求状态
 */
import { requestedMessage } from "@/utils/asynchronous";
/**
 * 接口
 */
import LoginPort from "@/api/Login/LoginPort";

/**
 * 获取本地存储数据
 */
const localDataValue = StorageService.localData.name;
/**
 * 登录信息
 */
const user = reactive({
  name: localDataValue ?? "spjy01",
  password: "12345678",
});

// 表单校验规则
const rules = {
  username: {
    required: true,
    validator(rule, value) {
      if (!value.trim().length) {
        return new Error("请输入用户名");
      }
      return true;
    },
  },
  password: {
    required: true,
    validator: (rule, value) => {
      if (!value.trim().length) {
        return new Error("请输入密码");
      }
      return true;
    },
  },
};

/**
 * 验证登录表单 通过后登录并保存 name 和 token，然后查询登录账号的权限做出对应跳转
 */
async function handleLogin() {
  try {
    requestedMessage(
      async () => {
        const { message, msg } = await LoginPort.login(
          user.name,
          user.password
        );
        // 保存数据到本地存储
        StorageService.saveToLocalStorage("token", message);
          //登录成功
        window.location.href = '/home'
        return msg;
      },
      {
        showSuccess: true,
        fullscreenLoading: true,
      }
    );
  } catch (error) {
    console.log("异常", error);
  }
}
</script>
